package com.websuites.ejb.invoke;

import java.lang.reflect.Method;
import java.util.Map;

import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.websuites.core.context.SpringBeanConnector;
import com.websuites.ejb.jndi.JNDIUtil;
import com.websuites.utils.LogUtil;

@Remote
@Stateless(mappedName = "EjbServiceInvokeBean")
public class EjbServiceInvokeBean implements EJBServiceInvoke {
	public Object invoke(Map<String, Object> ejbParam) {
		Object result = null;
		String invokeClassName = (ejbParam.get("target") == null) ? null : (String) ejbParam.get("target");
		String invokeMethod = (ejbParam.get("service") == null) ? null : (String) ejbParam.get("service");
		Object[] ejbMethodParams = (ejbParam.get("serviceParams") == null) ? null : (Object[]) ejbParam.get("serviceParams");
		LogUtil.info("invoke target: "+invokeClassName);
		LogUtil.info("invoke method: "+invokeMethod);
		LogUtil.info("invoke method request parameters: "+ejbMethodParams);
		if (invokeClassName != null && invokeClassName.trim().length() > 0 && invokeMethod != null && invokeMethod.trim().length() > 0) {
			try {
				Class paramClass[] = null;
				if (ejbMethodParams != null && ejbMethodParams.length>0) {
					int methodParamSize = ejbMethodParams.length;
					paramClass = new Class[methodParamSize];
					for (int i = 0; i < methodParamSize; ++i) {
						paramClass[i] = ejbMethodParams[i].getClass();
					}
				}
				//spring bean, use spring autowise
				Object obj = SpringBeanConnector.getBean(invokeClassName);

		        //ejb
				if(obj==null){
					obj = JNDIUtil.lookup(invokeClassName);
				}
				
				//reflect java
				if(obj==null){
					Class cls = Class.forName(invokeClassName);
					obj = cls.newInstance();
				}
				
				if(obj!=null){
					Method method = obj.getClass().getDeclaredMethod(invokeMethod, paramClass);
					result = method.invoke(obj, ejbMethodParams);
					LogUtil.info("EJB Bex invoke result:"+result);
				}else{
					LogUtil.info("invoke target: "+invokeClassName+" can not be bound to spring bean or ejb service or java class in server");
				}
			} catch (Exception e) {
				LogUtil.error(e.getMessage());
				e.printStackTrace();
				return null;
			}
		}
		return result;
	}
}